import { db, models } from '../../db';

const {
  config_item: ConfigItemModel,
  user: UserModel,
  user_item: UserItemModel,
  user_log_assets: UserLogAssetsModel,
  user_log_silver: UserLogSilverModel,
} = models;

export const shopBuy = async (user_id: string, data: Record<string, any>) => {
  const transaction = await db.transaction();

  return new Promise(async (resolve, reject) => {
    try {
      const { id, num } = data;

      if (num <= 0) {
        return;
      }

      const itemInfo = await ConfigItemModel.findOne({ where: { id: id } });

      if (!itemInfo) {
        return;
      }

      const { gold: itemGold } = itemInfo.dataValues;
      const price = itemGold * num;

      const userInfo = await UserModel.findOne({ where: { id: user_id } });
      const { gold } = userInfo!.dataValues;

      if (gold < price) {
        return reject('金币不足');
      }

      // 减掉花费
      await UserModel.update({ gold: gold - price }, { where: { id: user_id }, transaction });
      // 增加物品
      const userItem = await UserItemModel.findOne({
        where: { user_id, item_id: id },
        transaction,
      });

      if (!userItem) {
        const newItem = await UserItemModel.create(
          {
            user_id,
            item_id: id,
            count: num,
          },
          {
            transaction,
          },
        );
        await UserLogAssetsModel.create(
          {
            user_id,
            type: 'get',
            assets_id: newItem.dataValues.id,
            assets_type: 'item',
            count: num,
            reason_type: 'shop',
            reason: '购买道具',
          },
          {
            transaction,
          },
        );
      } else {
        await UserItemModel.update(
          {
            count: userItem.dataValues.count + num,
          },
          {
            where: { id: userItem.dataValues.id },
            transaction,
          },
        );
        await UserLogAssetsModel.create(
          {
            user_id,
            type: 'get',
            assets_id: userItem.dataValues.id,
            assets_type: 'item',
            count: num,
            reason_type: 'shop',
            reason: '购买道具',
          },
          {
            transaction,
          },
        );
      }

      await transaction.commit();
      return resolve('ok');
    } catch (error) {
      await transaction.rollback();
      return reject(error);
    }
  });
};
